package data;

import java.util.ArrayList;

import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;

public class DataSet extends AbstractTableModel implements TableModel {

	private ArrayList<DataRecord> datalist;
	
	public DataSet() {
		datalist = new ArrayList<DataRecord>();
	}
	
	public DataSet( ArrayList<DataRecord> data ) {
		super();
		this.datalist = data;
	}
	
	@Override //Spalten
	public int getColumnCount() {
		if ( datalist.size() > 0 ) {
			DataRecord data = datalist.get(0);
			return data.getSize();
		} else {
			return 0;
		}

	}

	@Override //Zeilen
	public int getRowCount() {
		return datalist.size();
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		DataRecord data = datalist.get( rowIndex );
		Object output = data.getEntrys().get( columnIndex ).getValue();
		return output;
	}
	
	public void add( DataRecord record ) {
		datalist.add( record );
	}
	public String getColumnName( int row ) {
		String out = new String();
		DataRecord data = datalist.get( 0 );
		out = data.getEntrys().get( row ).getName();
		return out;
	}
	public void printData() {
		for( DataRecord r : datalist ) {
			System.out.println( r.toString() );
		}
	}
	
	public void sortBy( String variable, Boolean ascending ) {
		
		boolean global_switch = true;
		while( global_switch ) {
			global_switch = false;

			Object last = datalist.get( 0 ).getValueByName( variable );
			for( int i=1; i<this.datalist.size(); i++ ) {
				boolean actual_switch = false;
				DataRecord record = datalist.get( i );
				Object actual = record.getValueByName( variable );
				if ( actual instanceof Integer ) {
					if( ascending ) {
						if( (Integer) last > (Integer) actual ) {
							actual_switch = true;
						}
					} else {
						if( (Integer) last < (Integer) actual ) {
							actual_switch = true;
						}
					}
					last = actual;
				}
				if( actual_switch ) {
					global_switch = true;
					DataRecord element = this.datalist.remove( i );
					this.datalist.add( i -1, element );
				}
			}
			
		}
	}
	public ArrayList<DataRecord> getDataList() {
		return this.datalist;
	}

}
